/*

gcc pp.c -lpthread && ./a.out

*/
#include <assert.h>
#include <stdio.h>
#include <pthread.h>

int flag;
pthread_mutex_t mutex;
pthread_cond_t cv;

void* produce(void* arg)
{
    while (1)
    {
        pthread_mutex_lock(&mutex);
        while (flag == 0)
            pthread_cond_wait(&cv, &mutex);
        printf("ping\n");
        flag--;
        pthread_cond_signal(&cv);
        pthread_mutex_unlock(&mutex);
    }
}

void* consume(void* arg)
{
    while (1)
    {
        pthread_mutex_lock(&mutex);
        while (flag == 1)
            pthread_cond_wait(&cv, &mutex);
        printf("pong\n");
        flag++;
        pthread_cond_signal(&cv);
        pthread_mutex_unlock(&mutex);
    }
}

int main(int argc, char** argv)
{
    flag = 1;

    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cv, NULL);

    pthread_t pid[2];
    pthread_create(pid, NULL, produce, NULL);
    pthread_create(pid+1, NULL, consume, NULL);

    pthread_join(pid[0], NULL);
    pthread_join(pid[1], NULL);
}